//
//  TF_NewFunctionView.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/2/17.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

class TF_NewFunctionView: UIView {
    //拖动手势结束时
    @objc public var sliderValueBlock: ((CGFloat) -> ())?
    //过程中
    @objc public var sliderValueChangeBlock: ((CGFloat) -> ())?
    //单击
    @objc public var sliderTapGestureBlock: ((CGFloat) -> ())?
  
    //传设置的倍速
    @objc public var playbackRateBlock: ((CGFloat) -> ())?
  

    @objc public var TimeLabelShow:Bool = false
    
    @objc public let backBtn = TalkfunIncreaseButton()
    @objc public let refreshBtn = TalkfunIncreaseButton()
    @objc public let networkBtn = TalkfunIncreaseButton()
    @objc public let playBtn = TalkfunIncreaseButton()

    @objc public let isPlayImageView = UIImageView()
    @objc public let slider = UISlider()
    @objc public var touch:Bool = false
    //在滑动过程中
    @objc public var isChange:Bool = false
    @objc public let timeLabel = UILabel()
    //总时长
    @objc public let totalTimeLabel = UILabel()
 
    @objc public var timer:Timer?
    @objc public var isPlay:Bool = false
    //播放了多少秒
    @objc public var playDuration:CGFloat = 0


  
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backBtn.setImage(UIImage.init(named: "HTLive.bundle/back_5.png"), for: .normal)
        self.addSubview(self.backBtn)

        self.refreshBtn.setImage(UIImage.init(named: "HTLive.bundle/shuaxin.png"), for: .normal)
        self.addSubview(self.refreshBtn)
        
        self.networkBtn.setImage(UIImage.init(named: "HTLive.bundle/neticon.png"), for: .normal)
        self.addSubview(self.networkBtn)
        

        self.timeLabel.textColor = UIColor.white
        self.timeLabel.font = UIFont.PingFang(size: 13)
        self.addSubview(self.timeLabel)
        self.timeLabel.text = "00:00:00";


        self.addSubview(self.slider)
        self.addSubview(self.playBtn)
       
        
        self.isPlayImageView.image = UIImage.init(named: "HTLive.bundle/zanting1.png")
        self.playBtn.addSubview(self.isPlayImageView)

        self.backgroundColor = UIColor.clear
        self.playBtn.isHidden = true
        self.slider.isHidden = true

        
        self.playBtn.isHidden = false
        self.isPlayImageView.isHidden  = false
        self.playBtn.layer.cornerRadius = 25;

        self.slider.isHidden = false
        self.timeLabel.isHidden = false
        self.touch = false
       
        
        let sliderTap = UITapGestureRecognizer.init(target: self, action: #selector(sliderTap))
        self.slider.addGestureRecognizer(sliderTap)
     
        
        self.slider.isContinuous = true
        self.slider.value = 0.0;
        self.slider.isUserInteractionEnabled = true
        ///所有触摸取消事件
        self.slider.addTarget(self, action: #selector(eventTouchChanged), for: .touchCancel)
        //选中
        self.slider.addTarget(self, action: #selector(sliderThumbTouch), for: .touchDown)
        //移动过程中
        self.slider.addTarget(self, action: #selector(ControlEventValueChanged), for: .valueChanged)
        //拖动结束
        self.slider.addTarget(self, action: #selector(sliderThumbUnTouch), for: [.touchUpOutside,.touchDragInside])
        
            
        self.slider.setThumbImage(UIImage.init(named: "HTLive.bundle/jinduO"), for: UIControl.State.normal)
        
        self.slider.setMinimumTrackImage(UIImage.init(named: "HTLive.bundle/jindu2"), for: .normal)
        self.slider.setMaximumTrackImage(UIImage.init(named: "HTLive.bundle/jindu1"), for: .normal)
       
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        let backBtnW:CGFloat = 30
        
        self.backBtn.frame = CGRect(x: 0, y: 0, width: backBtnW, height: backBtnW)
        
        
        let refreshBtnW:CGFloat = backBtnW
        let refreshBtnX = self.frame.size.width - refreshBtnW
       
        self.refreshBtn.frame = CGRect(x: refreshBtnX, y: 0, width: refreshBtnW, height: refreshBtnW)

        let networkBtnW:CGFloat = refreshBtnW
        let networkBtnY = self.frame.size.height - networkBtnW
        self.networkBtn.frame = CGRect(x: refreshBtnX, y: networkBtnY, width: networkBtnW, height: networkBtnW)
        
        let timeLabelW:CGFloat = 70
        let timeLabelH = refreshBtnW
        self.timeLabel.frame = CGRect(x: 0, y: networkBtnY, width: timeLabelW, height: timeLabelH)
    
        let sliderH :CGFloat = timeLabelH
        self.slider.frame = CGRect(x: backBtnW + 10, y: networkBtnY, width: self.frame.size.width - backBtnW - backBtnW - 10 - 10, height: sliderH)
        
        
        self.playBtn.frame = CGRect(x: (self.frame.size.width - 50.0)/2.0, y: (self.frame.size.height - 50.0)/2.0, width: 50.0, height: 50.0)
        

        self.isPlayImageView.frame = CGRect(x: (self.playBtn.frame.size.width - 30.0 )/2, y: (self.playBtn.frame.size.height - 30.0)/2, width: 30.0, height: 30.0)
        
    }
    
    //中断
    @objc func sliderTap(sliderTap:UITapGestureRecognizer) {
        if (self.isChange ) {
            return;
        }
        
        if (sliderTap.state == .ended) {
            if (!self.touch) {
                
                
                let location  = sliderTap.location(in: self.slider)
                
                let x:CGFloat  = location.x
                let r:CGFloat = x / self.slider.frame.size.width
                let value = CGFloat((self.slider.maximumValue - self.slider.minimumValue)) * r
                
                self.slider.setValue(Float(value), animated: true)
          
            }
        }
        
         let text =  TalkfunSharedTools.getTimeStr( CGFloat(self.slider.value)) as String
         self.timeLabel.text = text
        //单点
        if (self.sliderTapGestureBlock != nil) {
            self.sliderTapGestureBlock?(CGFloat(self.slider.value))
        }
        
       
    }
    //过程中
    @objc func ControlEventValueChanged(slider:UISlider) {
        self.touch = false
        
        let text =  TalkfunSharedTools.getTimeStr( CGFloat(slider.value)) as String
        self.timeLabel.text = text
        
        if(self.sliderValueChangeBlock != nil) {
            self.sliderValueChangeBlock?(CGFloat(slider.value))
        }
        self.isChange = true
    }
    //点中
    @objc func sliderThumbTouch(slider:UISlider) {
        self.touch = true
        
        if((self.timer) != nil)
        {
            self.timer?.invalidate()
            self.timer = nil;
        }
        
    }
    //所有触摸取消事件，即一次触摸因为放上了太多手指而被取消，或者被上锁或者电话呼叫打断。
    @objc func eventTouchChanged(slider:UISlider) {
        self.sliderThumbUnTouch(slider: slider)
    }
    
    
    //结束或者取消
    @objc func sliderThumbUnTouch(slider:UISlider) {
        self.touch = false
        self.isChange = false
        
        if(self.sliderValueBlock != nil) {
            self.sliderValueBlock?(CGFloat(slider.value))
        }
      

        self.initTime()
    }

   func initTime()
    {
        if((self.timer) != nil)
        {
        }else
        {
            self.timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(timeFireMethod), userInfo: nil, repeats: true)

            RunLoop.main.add(self.timer! , forMode: RunLoop.Mode.default)
        }
    }
    
    @objc public func buttonsAddTarget(target:NSObject, action:Selector) {
        
        self.backBtn.addTarget(target, action: action, for: .touchUpInside)
        self.refreshBtn .addTarget(target, action: action, for: .touchUpInside)
        self.networkBtn .addTarget(target, action: action, for: .touchUpInside)
   
      }
    
    //是否在播放
    @objc public func play(state:Bool)
    {
        if (self.isPlay != state||(self.isPlay == false && state == false)) {
            self.isPlay = state
            
            let imageName = state ? "暂停1.png" : "播放1.png"
            
            self.isPlayImageView.image = UIImage.init(named: imageName)
            
            self.playBtn.isSelected = !state;
            
            self.initTime()


        }
        
        //在播放
        if ( self.isPlay==true && self.isHidden == false) {
            self.initTime()

        }
    }

    //配置总时长
    @objc public func totalTimeLabelShow(state:Bool)
    {
        TimeLabelShow = state;
        let duration = self.slider.maximumValue;
        let text =  TalkfunSharedTools.getTimeStr(CGFloat(duration)) as String
        self.totalTimeLabel.text = text
        
    
    }
    //配置当前播放时间
    @objc public func setDuration(duration:CGFloat)
    {
        //不是移动过程中
//        if (self.isChange == false) {
            if (self.touch == false && fabs(self.slider.value - Float(duration)) > 1.0) {
             
                self.slider.setValue(Float(duration), animated: true)
            }
            
            let text =  TalkfunSharedTools.getTimeStr(CGFloat(duration)) as String
            self.timeLabel.text = text
            let totalDuration = self.slider.maximumValue;
            self.totalTimeLabel.text = TalkfunSharedTools.getTimeStr(CGFloat(totalDuration)) as String
//        }
    }
    deinit {
//        self.timeFireMethod()
//            print("对象被delloc没有造成循环引")

        }

    @objc func timeFireMethod()
    {
        if((self.timer) != nil)
        {
            self.timer?.invalidate()
            self.timer = nil;
        }
    
        self.isHidden = true
        
    }
   
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
